import React, { useState, useEffect } from 'react';
import { BrowserConfig, BrowserStatus, SaveBrowserConfig } from '../../../main/types/browser';
import { EditConfigModal } from '../../EditConfigModal';
const { ipcRenderer } = window.require('electron');

function StatusDisplay({ status }: { status: BrowserStatus | null | undefined }) {
  if (!status) return null;
  
  const timeSinceLastCheck = Date.now() - status.lastChecked;
  const isStale = timeSinceLastCheck > 10000; // 如果超过10秒没有更新，认为状态可能已过期
  
  const getStatusText = () => {
    if (isStale) return '状态未知';
    if (status.inProgress) {
      return status.action === 'starting' ? '启动中...' : '停止中...';
    }
    return status.isRunning ? '运行中' : '已停止';
  };

  const getStatusColor = () => {
    if (isStale) return '#757575';
    if (status.inProgress) return '#fb8c00';
    return status.isRunning ? '#2e7d32' : '#c62828';
  };
  
  return (
    <div style={{ 
      marginTop: '10px',
      fontSize: '14px'
    }}>
      <strong>状态：</strong>
      <span style={{ 
        color: getStatusColor(),
        display: 'inline-flex',
        alignItems: 'center',
        gap: '4px'
      }}>
        {getStatusText()}
        {isStale && (
          <span style={{ 
            fontSize: '12px',
            color: '#757575' 
          }}>
            ({Math.floor(timeSinceLastCheck / 1000)}秒前更新)
          </span>
        )}
      </span>
    </div>
  );
}

function Home() {
  const [configs, setConfigs] = useState<BrowserConfig[]>([]);
  const [instanceStatuses, setInstanceStatuses] = useState<Map<string, BrowserStatus>>(new Map());
  const [loading, setLoading] = useState<boolean>(true);
  const [error, setError] = useState<string | null>(null);
  const [actionInProgress, setActionInProgress] = useState<string | null>(null);
  const [editingConfig, setEditingConfig] = useState<BrowserConfig | null>(null);
  const [showAddModal, setShowAddModal] = useState<boolean>(false);

  useEffect(() => {
    loadConfigs();
    updateStatus(); // 立即更新一次状态
    const statusInterval = setInterval(updateStatus, 1000);
    
    // 监听状态更新事件
    ipcRenderer.on('browser-status-update', (_:any, id: string, status: BrowserStatus) => {
      setInstanceStatuses(prev => {
        const newMap = new Map(prev);
        if (status) {
          newMap.set(id, {
            isRunning: Boolean(status.isRunning),
            lastChecked: Number(status.lastChecked) || Date.now(),
            inProgress: Boolean(status.inProgress),
            action: status.action
          });
        } else {
          newMap.delete(id);
        }
        return newMap;
      });
    });
    
    return () => {
      clearInterval(statusInterval);
      ipcRenderer.removeAllListeners('browser-status-update');
    };
  }, []);

  const showError = (message: string) => {
    setError(message);
    setTimeout(() => setError(null), 3000);
  };

  const loadConfigs = async () => {
    try {
      setLoading(true);
      const result = await ipcRenderer.invoke('get-browser-configs');
      if (result.success === false) {
        showError(result.error || '加载配置失败');
        return;
      }
      setConfigs(result);
    } catch (error) {
      showError(error instanceof Error ? error.message : '加载配置失败');
      console.error('Failed to load configs:', error);
    } finally {
      setLoading(false);
    }
  };

  const updateStatus = async () => {
    try {
      const statuses = await ipcRenderer.invoke('get-all-browser-statuses');
      // 确保状态对象有效
      if (statuses && typeof statuses === 'object') {
        const statusMap = new Map<string, BrowserStatus>();
        Object.entries(statuses).forEach(([id, status]) => {
          if (status && typeof status === 'object') {
            const typedStatus = status as {
              isRunning?: boolean;
              lastChecked?: number;
              inProgress?: boolean;
              action?: 'starting' | 'stopping';
            };
            
            // 确保所有必需的字段都存在并且类型正确
            statusMap.set(id, {
              isRunning: Boolean(typedStatus.isRunning),
              lastChecked: Number(typedStatus.lastChecked) || Date.now(),
              inProgress: Boolean(typedStatus.inProgress),
              action: typedStatus.action
            });
          }
        });
        setInstanceStatuses(statusMap);
      }
    } catch (error) {
      console.error('Failed to update status:', error);
    }
  };

  const handleSubmit = async (config: SaveBrowserConfig) => {
    try {
      setActionInProgress('saving');
      const result = await ipcRenderer.invoke('save-browser-config', config);
      if (!result.success) {
        showError(result.error || '保存配置失败');
        return;
      }

      await loadConfigs();
      setShowAddModal(false);
    } catch (error) {
      showError(error instanceof Error ? error.message : '保存配置失败');
      console.error('Failed to save config:', error);
    } finally {
      setActionInProgress(null);
    }
  };

  const handleLaunch = async (config: BrowserConfig) => {
    try {
      setActionInProgress(`launching-${config.id}`);
      const result = await ipcRenderer.invoke('launch-browser', config);
      if (!result.success) {
        showError(result.error || '启动浏览器失败');
      }
      // 立即更新状态
      await updateStatus();
    } catch (error) {
      showError(error instanceof Error ? error.message : '启动浏览器失败');
      console.error('Failed to launch browser:', error);
    } finally {
      setActionInProgress(null);
    }
  };

  const handleStop = async (id: string) => {
    try {
      setActionInProgress(`stopping-${id}`);
      const result = await ipcRenderer.invoke('stop-browser', id);
      if (!result.success) {
        showError(result.error || '停止浏览器失败');
      }
      // 立即更新状态
      await updateStatus();
    } catch (error) {
      showError(error instanceof Error ? error.message : '停止浏览器失败');
      console.error('Failed to stop browser:', error);
    } finally {
      setActionInProgress(null);
    }
  };

  const handleDelete = async (id: string) => {
    // 显示确认对话框
    const confirmed = window.confirm('删除实例将会同时删除该实例的用户数据目录，是否确认删除？');
    if (!confirmed) {
      return;
    }

    try {
      setActionInProgress(`deleting-${id}`);
      const result = await ipcRenderer.invoke('delete-browser-config', id);
      if (!result.success) {
        showError(result.error || '删除配置失败');
      } else {
        await loadConfigs();
      }
    } catch (error) {
      showError(error instanceof Error ? error.message : '删除配置失败');
      console.error('Failed to delete config:', error);
    } finally {
      setActionInProgress(null);
    }
  };

  const handleEditConfig = (config: BrowserConfig) => {
    setEditingConfig(config);
  };

  const handleSaveEdit = async (updatedConfig: SaveBrowserConfig) => {
    try {
      setActionInProgress('updating');
      const result = await ipcRenderer.invoke('save-browser-config', updatedConfig);
      if (!result.success) {
        showError(result.error || '更新配置失败');
        return;
      }

      await loadConfigs();
      setEditingConfig(null); // 关闭编辑模态框
    } catch (error) {
      showError(error instanceof Error ? error.message : '更新配置失败');
      console.error('Failed to update config:', error);
    } finally {
      setActionInProgress(null);
    }
  };

  const handleCancelEdit = () => {
    setEditingConfig(null);
  };

  if (loading) {
    return (
      <div style={{ 
        display: 'flex', 
        justifyContent: 'center', 
        alignItems: 'center', 
        height: '100%' 
      }}>
        加载中...
      </div>
    );
  }

  return (
    <>
      <h1>浏览器实例管理器</h1>
      
      {error && (
        <div style={{
          padding: '10px',
          marginBottom: '20px',
          backgroundColor: '#ffebee',
          color: '#c62828',
          borderRadius: '4px'
        }}>
          {error}
        </div>
      )}
      
      <div style={{ marginBottom: '20px' }}>
        <button
          onClick={() => setShowAddModal(true)}
          style={{
            backgroundColor: '#1976d2',
            color: 'white',
            border: 'none',
            padding: '10px 20px',
            borderRadius: '4px',
            cursor: 'pointer',
            fontSize: '16px'
          }}
        >
          添加新实例
        </button>
      </div>

      <h2>浏览器实例列表</h2>
      {loading ? (
        <div>加载中...</div>
      ) : (
        <>
          <div style={{ 
            display: 'grid', 
            gap: '20px',
            gridTemplateColumns: 'repeat(auto-fill, minmax(300px, 1fr))'
          }}>
            {configs.map(config => (
              <div key={config.id} style={{
                border: '1px solid #e0e0e0',
                borderRadius: '8px',
                padding: '16px',
                backgroundColor: '#fff',
                boxShadow: '0 2px 4px rgba(0,0,0,0.1)'
              }}>
                <h3 style={{ margin: '0 0 10px 0' }}>{config.name}</h3>
                
                {config.userAgent && (
                  <div style={{ 
                    fontSize: '14px',
                    marginBottom: '10px',
                    wordBreak: 'break-all'
                  }}>
                    <strong>User Agent:</strong> {config.userAgent}
                  </div>
                )}
                
                {config.chromePath && (
                  <div style={{ 
                    fontSize: '14px',
                    marginBottom: '10px',
                    wordBreak: 'break-all'
                  }}>
                    <strong>Chrome路径:</strong> {config.chromePath}
                  </div>
                )}

                <div style={{ 
                  fontSize: '14px',
                  marginBottom: '10px',
                  wordBreak: 'break-all'
                }}>
                  <strong>用户数据目录:</strong> {config.userDataDir}
                </div>

                <StatusDisplay status={instanceStatuses.get(config.id)} />
                
                <div style={{ 
                  display: 'flex',
                  gap: '10px',
                  marginTop: '15px'
                }}>
                  {(!instanceStatuses.get(config.id)?.isRunning && !instanceStatuses.get(config.id)?.inProgress) && (
                    <button
                      onClick={() => handleLaunch(config)}
                      disabled={actionInProgress === `launching-${config.id}`}
                      style={{
                        padding: '8px 16px',
                        backgroundColor: '#2196f3',
                        color: 'white',
                        border: 'none',
                        borderRadius: '4px',
                        cursor: 'pointer',
                        opacity: actionInProgress === `launching-${config.id}` ? 0.7 : 1
                      }}
                    >
                      启动
                    </button>
                  )}
                  
                  {(instanceStatuses.get(config.id)?.isRunning && !instanceStatuses.get(config.id)?.inProgress) && (
                    <button
                      onClick={() => handleStop(config.id)}
                      disabled={actionInProgress === `stopping-${config.id}`}
                      style={{
                        padding: '8px 16px',
                        backgroundColor: '#f44336',
                        color: 'white',
                        border: 'none',
                        borderRadius: '4px',
                        cursor: 'pointer',
                        opacity: actionInProgress === `stopping-${config.id}` ? 0.7 : 1
                      }}
                    >
                      停止
                    </button>
                  )}
                  
                  <button
                    onClick={() => handleEditConfig(config)}
                    disabled={actionInProgress === `editing-${config.id}` || instanceStatuses.get(config.id)?.inProgress}
                    style={{
                      padding: '8px 16px',
                      backgroundColor: '#ff9800',
                      color: 'white',
                      border: 'none',
                      borderRadius: '4px',
                      cursor: instanceStatuses.get(config.id)?.inProgress ? 'not-allowed' : 'pointer',
                      opacity: actionInProgress === `editing-${config.id}` ? 0.7 : 1
                    }}
                  >
                    编辑
                  </button>
                  
                  <button
                    onClick={() => handleDelete(config.id)}
                    disabled={actionInProgress === `deleting-${config.id}` || instanceStatuses.get(config.id)?.isRunning}
                    style={{
                      padding: '8px 16px',
                      backgroundColor: instanceStatuses.get(config.id)?.isRunning ? '#bdbdbd' : '#757575',
                      color: 'white',
                      border: 'none',
                      borderRadius: '4px',
                      cursor: instanceStatuses.get(config.id)?.isRunning ? 'not-allowed' : 'pointer',
                      opacity: actionInProgress === `deleting-${config.id}` ? 0.7 : 1
                    }}
                  >
                    删除
                  </button>
                </div>
              </div>
            ))}
          </div>
        </>
      )}

      {showAddModal && (
        <EditConfigModal
          mode="add"
          onSave={handleSubmit}
          onCancel={() => setShowAddModal(false)}
          isSaving={actionInProgress === 'saving'}
        />
      )}

      {editingConfig && (
        <EditConfigModal
          mode="edit"
          config={editingConfig}
          onSave={handleSaveEdit}
          onCancel={handleCancelEdit}
          isSaving={actionInProgress === 'updating'}
        />
      )}
    </>
  );
}

export default Home; 